package cn.sell.comm.model.bo;

import cn.sell.comm.model.po.TreePO;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Ace on 2017/6/12.
 */
public class TreeNode<T extends TreePO> {

    public static <T extends TreePO> List<Node> formatTree(List<T> list) {
        List<Node> nodes = new ArrayList<>();
        for (T node1 : list) {
            if ("".equals(node1.getParentNodeId()) || node1.getParentNodeId() == null) {
                nodes.add(findChildrenNode(new Node(node1, null), list));
            }
        }
        return nodes;
    }

    private static <T extends TreePO> Node findChildrenNode(Node node, List<T> list) {
        for (T node2 : list) {
            String nodeId = node.getNode().getNodeId();
            String parentNodeId = node2.getParentNodeId();
            if (nodeId.equals(parentNodeId)) {
                if (node.getChildrenNode() == null) {
                    node.setChildrenNode(new ArrayList<Node>());
                }
                node.getChildrenNode().add(findChildrenNode(new Node(node2, new ArrayList<Node>()), list));
            }
        }
        return node;
    }

}
